﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TrickingLibrary.Data;
using TrickingLibrary.Models;

namespace TrickingLibrary.Api.Controllers
{
    [ApiController]
    [Route("api/categories")]
    public class CategoryController:ControllerBase
    {
        private readonly AppDbContext _ctx;

        public CategoryController(AppDbContext ctx)
        {
            _ctx = ctx;
        }

        [HttpGet]
        public IEnumerable<Category> All() => _ctx.Categories.ToList();

        [HttpGet("{id}")]
        public Category Get(string id) => _ctx.Categories
            .FirstOrDefault(x => x.Id.Equals(id,
                StringComparison.InvariantCultureIgnoreCase));


        [HttpGet("{Id}/tricks")]
        public IEnumerable<Trick> ListCategoryTrick(string Id) =>
            _ctx.TrickCategories
                .Include(x => x.Trick)
                .Where(x => x.CategoryId.Equals(Id, StringComparison.InvariantCultureIgnoreCase))
                .Select(x => x.Trick)
                .ToList();
                

        [HttpPost]
        public async Task<Category> Create([FromBody] Category category)
        {
            _ctx.Add(category);
            await _ctx.SaveChangesAsync();
            return category;
        }


        [HttpPut]
        public async Task<Category> Update([FromBody] Category category)
        {
            if(string.IsNullOrEmpty(category.Id))
            {
                return null;
            }

            _ctx.Add(category);
            await _ctx.SaveChangesAsync();
            return category;
        }


        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(string id)
        {
            var category = _ctx.Categories.FirstOrDefault(x => x.Id.Equals(id));
            category.Deleted = true;
            await _ctx.SaveChangesAsync();
            return Ok();
        }
        
    }
}